<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="课程名称">
        <el-input v-model="addData.name" placeholder="请输入课程名称"  style="width:200px" />
      </el-form-item>
      <!-- 讲师头像：TODO -->
      <el-form-item label="列表图片">
        <!-- 头衔缩略图 -->
        <pan-thumb :image="addData.pic" />
        <!-- 文件上传按钮 -->
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="imagecropperShow = true"
          >上传图片
        </el-button>
        <!--v-show：是否显示上传组件
:key：类似于id，如果一个页面多个图片上传控件，可以做区分
:url：后台上传的url地址
@close：关闭上传组件
@crop-upload-success：上传成功后的回调 -->
        <image-cropper
          v-show="imagecropperShow"
          :width="70"
          :height="70"
          :key="imagecropperKey"
          :url="BASE_API + '/oss/fileUpload'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"
        />
      </el-form-item>

    <el-form-item label="课程上架">
      
        <el-switch 
          v-model="addData.coursePutaway"
          active-text="上架"
          inactive-text="下架">
        </el-switch>
      
    </el-form-item>


    <el-form-item label="授课老师">
      <el-select v-model="addData.teacherId" placeholder="请选择老师">
          <el-option
              v-for="item in teachers"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
    </el-form-item>
 

      <el-form-item label="课程费">
        <el-input v-model="addData.courseMoney" placeholder=""  style="width:200px">
        <template slot="prepend">¥：</template>
        </el-input>
      </el-form-item>

      <el-form-item label="赠送积分">
        <el-input v-model="addData.point" placeholder="参加活动时赠送的积分"  style="width:200px"/>  
        
      </el-form-item>



      <el-form-item label="创建时间">

         <div class="block">
          <el-date-picker
            v-model="addData.createDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </div>
      </el-form-item>

    

      <el-form-item label="课程简介">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
          v-model="addData.description"  style="width:400px">
        </el-input>
      </el-form-item>

      <el-form-item label="排序号：">
        <el-input-number
          v-model="addData.sortId"
          controls-position="right"
          :min="0"
        />请填写排序号,数字越小越靠前
      </el-form-item>

      
      <el-form-item label="课程设置">

            <div style="text-align: left">
                <el-transfer
                  style="text-align: left; display: inline-block"
                  v-model="chapterValue"
                  filterable
                  :left-default-checked="[]"
                  :right-default-checked="[]"
                  :render-content="renderFunc"
                  :titles="['备选章节', '已选章节']"
                  :button-texts="['到左边', '到右边']"
                  :format="{
                    noChecked: '${total}',
                    hasChecked: '${checked}/${total}'
                  }"
                  @change="handleChange"
                  :data="data">
                  </el-transfer>
                   
                   <div style="margin-top: 15px;">
                      <el-input placeholder="在此添加新章节" v-model="input3" class="input-with-select" style="width:400px">
                        <el-select v-model="select" slot="prepend" placeholder="重要等级" style="width:100px">
                          <el-option label="1" value="1"></el-option>
                          <el-option label="2" value="2"></el-option>
                          <el-option label="3" value="3"></el-option>
                          <el-option label="4" value="4"></el-option>
                          <el-option label="5" value="5"></el-option>
                          <el-option label="6" value="6"></el-option>
                        </el-select>
                        <el-button slot="append" icon="el-icon-search" @click="addchapter()">添加新章节</el-button>
                      </el-input>
                    </div>
              </div>

      </el-form-item>


      <el-form-item>
      
        <div style="float:left; margin-right:20px;">
          <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate()">保存</el-button>
         </div>
         <div class="grid-content bg-purple-light ">
            <router-link :to="'/list/course'">
            <el-button type="info" icon="el-icon-back">返回</el-button>
            </router-link>
          </div>
         
      

      </el-form-item>

    </el-form>
  </div>
</template>

<style>
  .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
    .el-select .el-input {
    width: 130px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>
<script>
import course from "@/api/course";
import ImageCropper from "@/components/ImageCropper";
import PanThumb from "@/components/PanThumb";

export default {
  components: { PanThumb, ImageCropper },
           
  data() {

  
    return {
        addchapterData:{
          title:"",
          sortId:1,
        },  
        input3: '',
        select: '',
        data: [],
        allAhapterList:[],
        chapterValue: [],
        value4: [],
        renderFunc(h, option) {
          return <span>{ option.key } - { option.label }</span>;
        },
      
      teachers:[],
      options: [ {
          value: '正在进行中',
          label: '正在进行中'
        }, {
          value: '已结束',
          label: '已结束'
        }, {
          value: '即将开始',
          label: '即将开始'
        }],
        hotOptions: [ {
          value: '1',
          label: '是'
        }, {
          value: '0',
          label: '否'
        }], 
      addData: {
        id:"",
        name:"",
        coursePutaway:true,
        courseMoney:"",
        salesVolume:"",
        emplName:"",
        emplId:"",
        createDate:"",
        point:"",
        sortId:"",
        description:"",
        teacherId:"",
        pic:"",
        serialNumber:"",
        chapers:[],
      },
      teacherName:{
          teacherName:"",
          teacherId:""
      },
      saveBtnDisabled: false, // 保存按钮是否禁用,
      imagecropperShow: false, //头像上传组件是否显示
      imagecropperKey: 0,
      BASE_API: process.env.BASE_API, //获取dev.env.js里面的地址
    };
  },
  created() {
    //页面渲染之前执行
    this.init();
    this.getChapterList();
    

  },
  watch: {
    //监听
    $route(to, from) {
      //路由变化方式，路由发生变化，方法就会执行
      this.init();
    },
  },
  methods: {
        addchapter(){
             this.addchapterData.title=this.input3;
             this.addchapterData.sortId=this.select;
             course.addChapterShow(this.addchapterData).then((response) => {
             this.allAhapterList = response.object;
             this.getChapterList();
    });
        },

        generateData (){
        const cdata = []; 
        console.log(this.allAhapterList)    
        for (let i = 1; i <=this.allAhapterList.length; i++) {
          cdata.push({
            key: i,
            label:this.allAhapterList[i-1].title+` ${ i }`,
            // disabled: i % 4 === 0
          });
        }     
        this.data=cdata;
        console.log(data)
      },
    getChapterList(){
        course.ChapterListShow().then((response) => {
        this.allAhapterList = response.object;
       
        console.log(this.allAhapterList)
         this.generateData();
    });

    },

     handleChange(chapterValue, direction, movedKeys) {
        console.log(chapterValue, direction, movedKeys);
        this.addData.chapers=chapterValue;
      },

    close() {
      //关闭上传头像组件
      this.imagecropperShow = false;
      //上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    cropSuccess(data) {
      //上传成功后返回的图片地址
      this.addData.pic = data.fileUrl;
      //上传头像成功
      this.imagecropperShow = false;
      //上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    init() {
      //判断路径有id值,做修改
      console.log(this.$route.params.id)
      if (this.$route.params && this.$route.params.id) {
        //从路径获取id值
        const id = this.$route.params.id;
        //调用根据id查询的方法
        this.getInfo(id);
         course.selectAllTeacherName().then((response) => {
             this.teachers = response.object;
         });
      } else {
        //路径没有id值，做添加
        //清空表单
         course.selectAllTeacherName().then((response) => {
             this.teachers = response.object;
         });
         this.addData= {
                id:"",
                name:"",
                coursePutaway:true,
                courseMoney:"",
                salesVolume:"",
                emplName:"",
                emplId:"",
                createDate:"",
                point:"",
                sortId:"",
                description:"",
                teacherId:"",
                pic:"",
                serialNumber:""
              }
        
      }
    },
    //根据讲师id查询的方法
    getInfo(id) {
      course.selectCoursesShow(id).then((response) => {
        console.log(response);
        this.addData = response.object;
    });

     
    },
    saveOrUpdate() {
      //判断修改还是添加
      //根据teacher是否有id
      if (!this.addData.id) {
        //添加
        this.addActivity();
      } else {
        //修改
        this.updateCourse();
      }
    },
    //修改轮播图的方法
    updateSlideShow() {
      course.updateSlideShow(addData).then((response) => {
        //提示信息
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        //回到列表页面 路由跳转
        this.$router.push( '/list/course');
      });
    },
    //添加轮播图的方法
    addActivity() {
      console.log(this.addData.chapers)
      course.addCoursesShow(this.addData).then((response) => {
        //添加成功
        //提示信息
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //回到列表页面 路由跳转
        this.$router.push( '/list/course' );
      });
    },

    updateCourse() {
      console.log(course)
      course.updateCourse(this.addData).then((response) => {
        //添加成功
        //提示信息
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //回到列表页面 路由跳转
        this.$router.push( "/list/course" );
      });
    },
  },
};
</script>
